import { baseUrl } from '@/config'
import cacheRequest from "./unit/cacheRequest"
import requestInterceptor from "./unit/requestInterceptor"


const defaultOptions: httpDefaultOption = {
	baseUrl: baseUrl,
	url: '',
	timeout: 60000,
	method: 'GET',
	header: {},
	data: {},
	dataType: 'json',
	responseType: 'text',
	loadingTitle: "加载中。。。",
	isLoading: false,
	showToast: true,
	needToken: false,
	isCache: false,
	cacheExpire: 600000,
}

export default function httpRequest(requestOption: httpDefaultOption){
	// 1、合并参数
	let options = Object.assign({},defaultOptions,requestOption)
	// 2、获取缓存
	const cacheData = cacheRequest(options)
	// 3、如果缓存的数据还生效的话则不在服务器获取数据
	if (cacheData) {
		return Promise.resolve(cacheData)
	}
	// 4、请求前参数处理
	try{
		options = requestInterceptor(options)
	}catch(e){
		//TODO handle the exception
		return Promise.reject(e)
	}
	return new Promise((resolve,reject)=>{
		uni.request({
			...options,
			success(res:any) {
				console.log('request success', res)
				resolve(res)
			},
			fail(err:any) {
				console.log('request fail', err)
				reject(err)
			},
			complete(res:any) {
				console.log('request complete', res)
			}
		})
	})
}

function checkNetwork(){
	uni.getNetworkType({
		success(res) {
			console.log('network success', res)
		},
		fail(err) {
			console.log('network fail', err)
		},
		complete(res) {
			console.log('network complete', res)
		}
	})
}

uni.addInterceptor('request',{
	invoke(args) {
		console.log('interceptor invoke', args)
	},
	success(args) {
		console.log('interceptor success', args)
	},
	fail(err) {
		console.log('interceptor fail', err)
	},
	complete(res) {
		console.log('interceptor complete', res)
	}
})

uni.addInterceptor({
	returnValue(args) {
		
	}
})


